package com.aiju.base.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * @auther: 佐为
 * @date: 2016.8.15
 * @Description: 用于viewPager 懒加载的fragment
 */

public abstract class BaseLazyFragment extends BaseFragment {

    private View mView;
    protected Activity context;
    protected boolean isPrepared = false;

    final View getLayoutView() {
        return mView;
    }

    final void removeParentView(View rootView) {
        if (rootView == null) {
            return;
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
    }

    @Override
    public final void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser && isPrepared) {
            lazyLoad();
        } else {
            if (isPrepared) {
                lazyHidden();
            }
        }
        super.setUserVisibleHint(isVisibleToUser);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (this.getUserVisibleHint() && isPrepared) {
            lazyLoad();
        }
    }

    protected abstract void lazyLoad();

    protected void lazyHidden() {
    }

    public abstract View createView(LayoutInflater inflater,
                                    ViewGroup container, Bundle savedInstanceState);

    @Override
    public final View onCreateView(LayoutInflater inflater,
                                   ViewGroup container, Bundle savedInstanceState) {
        isPrepared = false;
        if (mView == null) {
            mView = createView(inflater, container, savedInstanceState);
        }
        removeParentView(mView);
        this.isPrepared = true;
        return mView;
    }

    @Override
    public void onDestroy() {
        removeParentView(mView);
        super.onDestroy();
    }

}
